﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace BridgeWebSystemLib.Core.Util
{
    public class XmlUtil
    {
        /// <summary>
        /// 对象转换为XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize<T>(T obj)
        {
            try
            {
                XmlSerializer ser = new XmlSerializer(obj.GetType());
                MemoryStream ms = new MemoryStream();
                ser.Serialize(ms, obj);
                ms.Close();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 转换XML为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string xmlString)
        {
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
                XmlReader xmlReader = XmlReader.Create(xmlStream);
                Object obj = xmlSerializer.Deserialize(xmlReader);

                xmlReader.Close();
                xmlStream.Close();
                return (T)obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
